<?php

namespace haibao\user\data\payment\web;

class UserOrder extends \haibao\user\data\BaseMysql {
    
	public function __construct(){
		parent::__construct('\haibao\user\model\data\payment\web\UserOrder');
		$this->setConfig( \haibao\classlibrary\www\Config::CLASSLIBRARY_CONFIG_MYSQL_HAIBAO_USER );
		$this->setReadPerformance(true);
	}
	
	public function getOrderByOrderId($orderId){
	    $result = $this->query('select * from UserOrder where OrderId=%s limit 1', array(
	        $orderId
	    ));
	    return $result->fetch_assoc();
	}
	
	public function saveOrder($model){
	    $this->beginTranscation();
	    try {
	       $this->add($model);
	       $this->addOrderHistory($model->OrderId, $model->UserId, $model->ProductPrice, $model->ProductId, $model->PayCard, $model->PayStatus);
       } catch (\Exception $e) {
           $this->rollback();
           throw $e;
       }
       $this->endTranscation();
	}
	
	public function paySuccess($userId, $orderId){
	    $this->beginTranscation();
	    try {
	        $order = $this->getOrderByOrderId($orderId);
	        
	        // 修改支付订单状态
	        $this->updateStatusByOrderId($userId, $orderId, \haibao\user\model\data\payment\web\UserOrder::PAY_STATUS_SUCCESS);
	        
	        // 增加支付订单操作记录
	        $this->addOrderHistory($orderId, $userId, $order['ProductPrice'], $order['ProductId'], '支付宝', \haibao\user\model\data\payment\web\UserOrder::PAY_STATUS_SUCCESS);
            
            // 增加视频观看时间
            $data = new \haibao\user\data\payment\web\UserVip();
            $userVipId = $data->addUserVip($userId, $order['ProductId']);
            
            // 向redis中添加订单成功标识
            $cache = new \haibao\user\cache\Payment();
            $cache->setPaymentResult($userId, $orderId);
            
        } catch (\Exception $e) {
            $this->rollback();
            throw $e;
        }
        $this->endTranscation();
        return $userVipId;
	}
	
	public function updateStatusByOrderId($userId, $orderId, $status){
	    $this->query('update UserOrder set PayStatus=%s where OrderId=%s and UserId=%s limit 1', array(
	        $status, $orderId, $userId
	    ));
	}
	
	public function addOrderHistory($orderId, $userId, $productPrice, $productId, $payType, $status){
	    $this->query('insert into UserOrderHistory(OrderId, UserId, ProductPrice, ProductId, PayCard, PayStatus, PayTime) values(%s,%s,%s,%s,%s,%s,%s)', array(
	        $orderId, $userId, $productPrice, $productId, $payType, $status, date('Y-m-d H:i:s')
	    ));
	}
	
	public function getUniqid(){
	    $data = new \haibao\user\cache\Payment();
	    return $data->getUniqid();
	}
	
	public function getPaymentResult($userId, $orderId){
	    $cache = new \haibao\user\cache\Payment();
	    return $cache->getPaymentResult($userId, $orderId);
	}

}
